package com.type.service;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.dao.UserDAO;
import com.type.dao.TypeTenDAO;
import com.type.vo.AddresseeVO;
import com.type.vo.MailVO;
import com.vo.UserVO;

@Service("TypeTenService")
public class TypeTenService {
	@Resource(name="TypeTenDAO")
	private TypeTenDAO dao;
	@Resource(name="userDAO")
	private UserDAO userDAO;
	
	private String picutreDir;

	public void insertSendMailInfo(MailVO mail, String address, String addressCC) throws IllegalStateException, IOException, SQLException {
		String[] receive = address.split(",");
		String[] carbonCopy = null;
		if(addressCC!=null){
			carbonCopy = addressCC.split(",");
		}
		int mailNo = dao.selectMailNo();
		
		for(int i=0; i<receive.length; i++){
			AddresseeVO addressee = new AddresseeVO();
			addressee.setMailNo(mailNo);
			addressee.setType("수신");
			addressee.setAddress(receive[i]);
			String tempAddress = receive[i].substring(receive[i].indexOf("@"));
			String tempid = receive[i].substring(0, receive[i].indexOf("@"));
			if(tempAddress.equals("@daou.co.kr")){
				UserVO user = userDAO.selectUserById(tempid);
				if(user==null){
					addressee.setName("해당없음");
					addressee.setDept("해당없음");
				}
				else{
					addressee.setName(user.getName());
					addressee.setDept("[SI전략&지원본부]");
				}
			}
			dao.insertAddresseeInfo(addressee);
		}
		if(addressCC !=null){
			for(int i=0; i<carbonCopy.length; i++){
				AddresseeVO addressee = new AddresseeVO();
				addressee.setMailNo(mailNo);
				addressee.setType("참조");
				addressee.setAddress(carbonCopy[i]);
				String tempAddress = carbonCopy[i].substring(carbonCopy[i].indexOf("@"));
				String tempId = carbonCopy[i].substring(0, carbonCopy[i].indexOf("@"));
				if(tempAddress.equals("@daou.co.kr")){
					UserVO user = userDAO.selectUserById(tempId);
					if(user==null){
						addressee.setName("해당없음");
						addressee.setDept("해당없음");
					}else{
						addressee.setName(user.getName());
						addressee.setDept("[SI전략&지원본부]");
					}
				}
				dao.insertAddresseeInfo(addressee);
			}
		}
		
		mail.setMailNo(mailNo);		
		mail.setReceiveDate("notChk");
		mail.setReceiptChk(0);	//확인 안함
		mail.setCubbyhole(0);	//보관함메일 아님
		mail.setRecycleBin(0);	//휴지통메일 아님
		
		MultipartFile upfile = mail.getUpfile();		
		if(upfile!=null && !upfile.isEmpty()){		//(겹치기 방지위해 )첨부파일 이름 변경
			String fileName = upfile.getOriginalFilename();
			String extension = fileName.substring(fileName.lastIndexOf("."));
			long time = System.currentTimeMillis();
			String newFileName = time+extension;
			upfile.transferTo(new File(picutreDir, fileName));
			mail.setAttachedFile(newFileName);
		}
		dao.insertSendMailInfo(mail);
	}
	
}
